var path=require('path');
var assert=require('assert');
var request=require('supertest');
var app=require('../app.js');
var PostSchema=require('../lib/mongo').Post;

describe('posts',()=>{
    var agent=request.agent(app),title='test-1-title',content='test-1-content',postId;

    before(done=>{
        agent
            .post('/signin')
            .type('form')
            .field({name:'testUser',password:'testUser'})
            .redirects()
            .end(err=>{
                if(err)return console.error('signin err:\n',err),done(err);
                done();
            });
    });

    it('create-post',done=>{
        agent
            .post('/posts/create')
            .type('form')
            .field({title:title,content:content})
            .redirects()
            .end((err,res)=>{
                if(err)return console.error('create-post err:\n',err),done(err);
                postId=path.parse(res.redirects[0]).name;
                console.log('postId:',postId);
                assert(res.text.match(new RegExp(title)));
                done();
            });
    });


    it('edit-post',done=>{
        agent
            .post(`/posts/${postId}/edit`)
            .type('form')
            .field({title:title+'-eidt-1',content:content+'-eidt-1'})
            .redirects()
            .end((err,res)=>{
                if(err)return console.error('edit-post ERROR:\n',err),done(err);
                assert(res.text.match('编辑成功'));
                done();
            });
    });


    it('comment-post',done=>{
        agent
            .post(`/posts/${postId}/comment`)
            .type('form')
            .field({content:'test-comment-1'})
            .redirects()
            .end((err,res)=>{
                if(err)return console.error('comment-post ERROR:\n',err),done(err);
                assert(res.text.match(/test\-comment-1/));
                done();
            });
    });


    it('remove-post',done=>{
        agent
            .get(`/posts/${postId}/remove`)
            .redirects()
            .end((err,res)=>{
                if(err)return console.error('remove-post ERROR:\n',err),done(err);
                assert(!res.text.match(new RegExp(postId)));
                done();
            });
    });

});